package service

import (
	"dta-apk/model"
	"dta-apk/query/request"
	"dta-apk/query/response"
	"dta-apk/utils"
	"log"
	"strconv"
)

// 分页查询版本列表
func GetVersionList(query *request.VersionPageQuery) (model.PageResult, bool) {
	var vls []response.VersionList
	// 查询条件
	where := model.VersionModel{AppId: query.AppId}
	page := model.Pagination{
		PageNum:  query.PageNum,
		PageSize: query.PageSize,
		Where:    where,
	}
	// 分页查询
	var versions []model.VersionModel
	result, err := model.Page(page, &versions)
	if err != nil {
		return result, false
	}

	// 遍历转化
	for _, v := range versions {
		vl := response.VersionList{
			AppId:       query.AppId,
			VersionId:   strconv.Itoa(int(v.ID)),
			Name:        v.Name,
			VersionName: v.VersionName,
			VersionCode: v.VersionCode,
			Status:      versionStatus[v.Status],
			Desc:        v.Remark,
			CreateTime:  v.CreateTime,
		}
		vls = append(vls, vl)
	}
	result.Data = vls

	return result, true
}

// 添加新版本
func AddVersion(query *request.VersionAddQuery) (string, bool) {
	// 保存到本地
	apkFile := query.VersionApk
	filePath, fileName, error := utils.SaveToLocalFile(*apkFile)
	versionName, versionCode := utils.GetApkVersion(filePath)
	defer utils.DeleteFile(filePath)
	if error != nil {
		log.Println(error)
		return error.Error(), false
	}
	// 上传文件
	objectUrl := utils.PutFile(fileName, filePath)
	// 保存版本信息
	version := model.VersionModel{
		AppId:       query.AppId,
		Name:        query.VersionName,
		VersionCode: versionCode,
		VersionName: versionName,
		Type:        query.VersionType,
		Remark:      query.VersionDesc,
		Status:      VersionToPublished,
		CreateTime:  utils.NowDate(),
	}
	model.DbConn.Create(&version)
	// 保存文件信息
	file := model.FileModel{
		Name:   fileName,
		Path:   objectUrl,
		Type:   "apk",
		Belong: strconv.Itoa(int(version.ID)),
	}
	model.DbConn.Create(&file)
	return "版本添加成功", true
}

// 获取应用可发布的版本列表
func GetPublishVersion(appId string) response.PublishVersionRes {
	var pvr response.PublishVersionRes
	pvr.IsPublish = false
	// 查询应用信息
	var app model.AppModel
	result := model.FindById(&app, appId)
	if result {
		var vs []response.PublishVersionListRes
		// 应用状态正常情况下，可发布
		status := app.Status
		// 判断应用状态，正常情况下可发布
		if status == 1 {
			// 最后发布的版本
			appVersion := "0"
			versionId := ""
			latestVersion := GetLatestPublishVersion(app.ID)
			if latestVersion == nil {
				return pvr
			}
			appVersion = latestVersion.VersionCode
			versionId = strconv.Itoa(int(latestVersion.ID))
			// 查询最后发布版本的发布情况
			isPublish, publishCheck, nextCheck := GetVersionPublish(appId, versionId)
			if isPublish {
				vs = append(vs, response.PublishVersionListRes{
					VersionId:   latestVersion.ID,
					VersionName: latestVersion.Name,
					Plats:       publishCheck,
				})
				pvr.IsPublish = true
			}
			//
			// 查询比发布版本后的版本列表
			var versions []model.VersionModel
			vr := model.DbConn.Where("version_code > ?", appVersion).Find(&versions)
			if vr.Error == nil && vr.RowsAffected > 0 {
				pvr.IsPublish = true
				for _, v := range versions {
					vs = append(vs, response.PublishVersionListRes{
						VersionId:   v.ID,
						VersionName: v.Name,
						Plats:       nextCheck,
					})
				}
			}
			pvr.Versions = vs
		}
	}

	return pvr
}

// 查询应用最新发布的版本
func GetLatestPublishVersion(appId uint) *model.VersionModel {
	var publishVersion model.AppPublishModel
	result := model.DbConn.Order("publish_time DESC").Where("app_id = ?", appId).First(&publishVersion)
	if result.Error != nil || result.RowsAffected == 0 {
		return nil
	}
	var version model.VersionModel
	isExist := model.FindById(&version, publishVersion.VersionId)
	if !isExist {
		return nil
	}

	return &version
}

// 查询版本的审核信息
func GetVersionPublish(appId, versionId string) (bool, []response.PlatPublish, []response.PlatPublish) {
	isPublish := false
	var checkMap []response.PlatPublish
	var nextPublishMap []response.PlatPublish
	// 查询可发布的平台
	var plats []model.AppPlatModel
	result := model.FindAll(&plats, &model.AppPlatModel{AppId: appId})
	if result {
		for _, plat := range plats {
			// 查询平台的审核信息
			var versionCheckArray model.AppPublishModel
			result = model.FindAll(&versionCheckArray, &model.AppPublishModel{VersionId: versionId, Plat: plat.Plat})
			if result {
				// 当前版本可发布状态
				if versionCheckArray.PublishStatus == 1 && (versionCheckArray.CheckStatus == "1" || versionCheckArray.CheckStatus == "") {
					checkMap = append(checkMap, response.PlatPublish{
						Plat:      plat.Plat,
						IsPublish: false,
					})
				} else {
					checkMap = append(checkMap, response.PlatPublish{
						Plat:      plat.Plat,
						IsPublish: true,
					})
				}
				// 后续版本可发布状态
				if versionCheckArray.PublishStatus == 1 && (versionCheckArray.CheckStatus == "1" || versionCheckArray.CheckStatus == "2") {
					nextPublishMap = append(nextPublishMap, response.PlatPublish{
						Plat:      plat.Plat,
						IsPublish: true,
					})
				} else {
					nextPublishMap = append(nextPublishMap, response.PlatPublish{
						Plat:      plat.Plat,
						IsPublish: false,
					})
				}
				if versionCheckArray.CheckStatus == "2" {
					isPublish = true
				}
			} else {
				checkMap = append(checkMap, response.PlatPublish{
					Plat:      plat.Plat,
					IsPublish: true,
				})
				nextPublishMap = append(nextPublishMap, response.PlatPublish{
					Plat:      plat.Plat,
					IsPublish: true,
				})
			}
		}
	}
	return isPublish, checkMap, nextPublishMap

}

// 获取版本详细信息
func GetVersionInfo(versionId string) response.VersionInfoResult {
	var versionInfo response.VersionInfoResult
	// 查询版本的基础信息
	var version model.VersionModel
	isExist := model.FindById(&version, versionId)
	if isExist {
		versionInfo.AppId = version.AppId
		versionInfo.VersionId = strconv.Itoa(int(version.ID))
		versionInfo.VersionName = version.Name
		versionInfo.ApkVersion = version.VersionCode
		versionInfo.Desc = version.Remark
		// 查询版本在各个平台的发布信息
		versionInfo.Plates = GetVersionPlate(versionId)
	}
	return versionInfo
}

// 获取平台的发布信息
func GetVersionPlate(versionId string) []response.VersionPlate {
	var platesInfoList []response.VersionPlate
	var plateMap = make(map[string]response.VersionPlate)
	// 查询版本在各个平台的发布信息
	var plates []model.AppPublishModel
	result := model.DbConn.Where(&model.AppPublishModel{VersionId: versionId}).Order("publish_time asc").Find(&plates)
	if result.Error == nil && result.RowsAffected > 0 {
		for _, plate := range plates {
			plateInfo := response.VersionPlate{
				Result:      versionStatus[plate.PublishStatus],
				Msg:         plate.PublishDesc,
				PublishTime: plate.PublishTime,
				Plate:       plate.Plat,
			}
			plateMap[plate.Plat] = plateInfo
		}
	}
	// 每个平台取一条数据，先展示
	for _, v := range plateMap {
		platesInfoList = append(platesInfoList, v)
	}

	return platesInfoList
}

// 下载版本对应的apk文件
func DownloadApkOfVersion(versionId string) (string, string) {
	// 版本信息
	var version model.VersionModel
	result := model.FindById(&version, versionId)
	if !result {
		return "", ""
	}
	// 文件信息
	var apkFile model.FileModel
	result = model.FindOne(&apkFile, &model.FileModel{Belong: versionId})
	if !result {
		return "", ""
	}
	if apkFile.Path == "" {
		return "", ""
	}
	fileName := version.VersionCode + ".apk"
	// 下载到本地
	filePath, _ := utils.GetTempFile("apk")
	isSucc := utils.DownloadFsoFile(apkFile.Name, filePath)
	if isSucc {
		return fileName, filePath
	}
	log.Println("apk文件下载失败")
	return "", ""
}

// 版本状态
var versionStatus = map[int]string{
	1: "开发中",
	2: "测试中",
	3: "待发布",
	4: "已发布",
	5: "已上架",
	6: "审核中",
	7: "发布失败",
}

const VersionToPublished int = 3
const VersionPublished int = 4

// 应用状态
var appStatus = map[int]string{
	1: "正常",
	2: "下架",
	3: "停止更新",
}

// const PlatOppo = "oppo"
// const PlatVivo = "vivo"
// const PlatXiaomi = "xiaomi"
// const PlatHuawei = "huawei"
